package com.biz.primus.ms.customercenter.api;

import com.biz.primus.base.enums.order.OrderTypeEnum;
import com.biz.primus.base.vo.PageResult;
import com.biz.primus.base.vo.PromotionBasicInfoVo;
import com.biz.primus.base.vo.commodity.ProductListItemVo;
import com.biz.primus.common.utils.DateUtil;
import com.biz.primus.model.customercenter.vo.request.*;
import com.biz.primus.model.customercenter.vo.response.*;
import com.biz.primus.model.member.vo.MemberAddressVo;
import com.biz.primus.model.member.vo.MemberVo;
import com.biz.primus.model.oms.vo.*;
import com.biz.primus.model.promotion.vo.req.OrderPromotionReqDetailVo;
import com.biz.primus.model.promotion.vo.req.OrderPromotionReqVo;
import com.biz.primus.model.promotion.vo.req.ProductPromotionReqVo;
import com.biz.primus.model.promotion.vo.req.ProductPromotionTagReqItemVo;
import com.biz.primus.ms.base.api.BaseApiController;
import com.biz.primus.ms.customercenter.feign.member.MemberFeignClient;
import com.biz.primus.ms.customercenter.feign.member.OmsFeignClient;
import com.biz.primus.ms.customercenter.feign.member.ProductFrontendFeignClient;
import com.biz.primus.ms.customercenter.feign.member.PromotionFeignClient;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author liujun
 * @date 2017/11/15
 */
@RestController
@RequestMapping("soa/customerCenterService/")
@Api("客服中心相关接口文档")
@Slf4j
public class CustomerCenterApiService extends BaseApiController
{
    private final MemberFeignClient memberFeignClient;

    private final ProductFrontendFeignClient productFrontendFeignClient;

    private final OmsFeignClient omsFeignClient;

    private final PromotionFeignClient promotionFeignClient;


    @Autowired
    public CustomerCenterApiService(MemberFeignClient memberFeignClient, ProductFrontendFeignClient productFrontendFeignClient,
                                    OmsFeignClient omsFeignClient, PromotionFeignClient promotionFeignClient)
    {
        this.memberFeignClient = memberFeignClient;
        this.productFrontendFeignClient = productFrontendFeignClient;
        this.omsFeignClient = omsFeignClient;
        this.promotionFeignClient = promotionFeignClient;
    }

    /**
     * 根据手机号码判断是否是系统会员
     * @param vo
     */
    @PostMapping("isSysMemberByMobile")
    public SysMemberResponseVo isSysMemberByMobile(@RequestBody IfSysMemberRequestVo vo)
    {
        SysMemberResponseVo sysMemberResponseVo = new SysMemberResponseVo();
        MemberVo memberVo = memberFeignClient.findMemberVoByMobile(vo.getMobile());
        if(memberVo == null)
        {
            sysMemberResponseVo.setSuccess(false);
        }
        else
        {
            sysMemberResponseVo.setSuccess(true);
        }
        return sysMemberResponseVo;
    }

    /**
     * 根据会员绑定手机号码获取会员信息
     * @param vo
     */
    @PostMapping("getMemberInfoByMobile")
    public MemberInfoResponseVo getMemberInfoByMobile(@RequestBody MemberInfoRequestVo vo)
    {
        MemberInfoResponseVo memberInfoResponseVo = null;
        MemberVo memberVo = memberFeignClient.findMemberVoByMobile(vo.getMobile());
        if(memberVo != null)
        {
            //根据会员从oms查询 下列几个参数 然后封装返回
            OrderQueryVo vot = new OrderQueryVo();
            vot.setUserId(Long.valueOf(memberVo.getId()));
            OmsOrderHistoryVo voResp = omsFeignClient.getOrderHistoryByUserId(vot);
            /**
             * 最后下单订单号
             */
            String lastPlaceOrderCode = voResp.getLastOrderCode();
            /**
             * 最后下单订单时间
             */
            String lastPlaceOrderTime = DateUtil.format2String(voResp.getLastOrderTime());
            /**
             * 订单总数
             */
            Integer placeOrderNum = voResp.getOrderCount();
            /**
             * 消费总金额
             */
            Integer consumptionOrderMoney = voResp.getOrderAmount();
            try{
                memberInfoResponseVo = new MemberInfoResponseVo(
                        memberVo.getMemberName(), memberVo.getIdCardName(),
                        memberVo.getMobile(), memberVo.getNickName(),
                        DateUtil.formatToLocalDateTime(memberVo.getBirthday(), "yyyy-MM-dd"),
                        DateUtil.formatToLocalDateTime(memberVo.getRegTime(), null),
                        memberVo.getLevel(), memberVo.getLevelDesc(),
                        memberVo.getPoint(), lastPlaceOrderCode, lastPlaceOrderTime,
                        placeOrderNum, consumptionOrderMoney, memberVo.getState().getDesc(),
                        memberVo.getSexType().getDesc(), memberVo.getChannelType().getCode(), "");
                memberInfoResponseVo.setMemberId(memberVo.getId() == null ? "" : memberVo.getId().toString());
            } catch (ParseException e)
            {
                log.error(" date ParseException error");
            }
        }
        return memberInfoResponseVo;
    }

    /**
     * 根据手机号码注册为系统会员
     * @param vo
     */
    @PostMapping("registerByMobile")
    public RegistrMemberResponseVo registerByMobile(@RequestBody IfRegMemberRequestVo vo)
    {
        RegistrMemberResponseVo registrMemberResponseVo = new RegistrMemberResponseVo();
        registrMemberResponseVo.setSuccess(memberFeignClient.registerByMobile(vo.getMobile()));
        return registrMemberResponseVo;
    }

    /**
     * 根据会员id查询会员地址列表
     * 按照新增地址时间倒序排列
     * @param vo
     * @return
     */
    @PostMapping("getMemberAddressItem")
    public List<MemberAddressItemInfoResponseVo> getMemberAddressItem(MemberAddressItemInfoPageRequestVo vo)
    {
        List<MemberAddressItemInfoResponseVo> returnList = Lists.newArrayList();
        List<MemberAddressVo> addresss = memberFeignClient.getAllAddress(Long.valueOf(vo.getMemberId()));
        if (addresss != null && !addresss.isEmpty()) {
            addresss.stream().forEach(address -> {
                MemberAddressItemInfoResponseVo resp = new MemberAddressItemInfoResponseVo();
                BeanUtils.copyProperties(address, resp);
                returnList.add(resp);
            });
        }
        return returnList;
    }

    /**
     * 新增收货地址 考虑是否要设置默认
     * @param vo
     * @return
     */
    @PostMapping("addMemberAddessInfo")
    public AddMemberAddressResponseVo addMemberAddessInfo(@RequestBody AddMemberAddressRequestVo vo)
    {
        AddMemberAddressResponseVo resp = new AddMemberAddressResponseVo();
        resp.setSuccess(memberFeignClient.addMemberAddessInfo(vo));
        return resp;
    }

    /**
     * 根据会员id获取针对会员推荐的商品
     * 按照下单购买时间倒序排列
     * @param vo
     * @return
     *
     */
    @PostMapping("getMemberRecommendProductItem")
    public List<RecommendProductResponseVo> getMemberRecommendProductItem(@RequestBody RecommendProductItemInfoRequestVo vo)
    {
        List<RecommendProductResponseVo> returnList = Lists.newArrayList();
        List<ProductListItemVo> items = productFrontendFeignClient.recommendProducts(vo);
        if (items != null && !items.isEmpty()) {
            items.stream().forEach(item -> {
                RecommendProductResponseVo resp = new RecommendProductResponseVo();
                BeanUtils.copyProperties(item, resp);
                returnList.add(resp);
            });
        }
        return returnList;
    }

    /**
     * 根据关键字和参数分页查询商品
     * @param vo
     * @return
     */
    @PostMapping("findProductBykeyword")
    public PageResult<ProductListItemVo> findProductBykeyword(@RequestBody SearchKeywordProductRequestVo vo)
    {
        return productFrontendFeignClient.searchProduct(vo);
    }

    /**
     * 根据商品信息查询相似的商品（和查询推荐商品一致 只是查询的枚举选择相似的）
     * @param vo
     * @return
     */
    @PostMapping("findSimilarityProductByProductInfo")
    public List<SimilarityProductResponseVo> findSimilarityProductByProductInfo(@RequestBody SearchSimilarityProductRequestVo vo)
    {
        List<SimilarityProductResponseVo> returnList = Lists.newArrayList();
        List<ProductListItemVo> items = productFrontendFeignClient.recommendProducts(vo);
        if (items != null && !items.isEmpty()) {
            items.stream().forEach(item -> {
                SimilarityProductResponseVo resp = new SimilarityProductResponseVo();
                BeanUtils.copyProperties(item, resp);
                returnList.add(resp);
            });
        }
        return returnList;
    }

    /**
     * 根据会员id获取会员购买过的商品 是否需要分页 分页增加分页参数
     * 按照购买时间倒序排列
     * @param vo
     * @return
     */
    @PostMapping("getMemberBuyProductItem")
    public PageResult<OmsHistoryOrderProductVo> getMemberBuyProductItem(@RequestBody BuyProductItemInfoPageRequestVo vo)
    {
        OrderQueryVo orderQueryVo = new OrderQueryVo();
        orderQueryVo.setUserId(Long.valueOf(vo.getMemberId()));
        orderQueryVo.setPage(vo.getPage());
        orderQueryVo.setSize(vo.getSize());
        return omsFeignClient.getOrderProductByUserId(orderQueryVo);
    }

    /**
     * 根据会员信息获取会员所下的历史订单
     * 按照下单时间倒序排列
     * @param vo
     * @return
     */
    @PostMapping("getHistoryOrderByMemberInfo")
    public PageResult<OmsOrderVo> getHistoryOrderByMemberInfo(@RequestBody HistoryOrderPageRequestVo vo)
    {
        OrderQueryVo orderQueryVo = new OrderQueryVo();
        orderQueryVo.setUserId(Long.valueOf(vo.getMemberId()));
        orderQueryVo.setPage(vo.getPage());
        orderQueryVo.setSize(vo.getSize());
        return omsFeignClient.getOrderByUserId(orderQueryVo);
    }

    /**
     * 订单详情
     * @param orderCode
     * @return
     */
    @GetMapping("getOrderDetail")
    OmsOrderRespVo getOrderDetail(@ApiParam(value = "订单编码", required = true) @RequestParam("orderCode")
                                          String orderCode)
    {
        return omsFeignClient.getOrderDetail(orderCode);
    }

    /**
     * 根据请求商品信息查询可用的促销活动
     * @param vo
     * @return
     */
    @PostMapping("getPromotionsInfoByProductInfo")
    public List<ProductPromotionsInfoResponseVo> getPromotionsInfoByProductInfo(@RequestBody BuyProductRequestVo vo)
    {
        List<ProductPromotionsInfoResponseVo> returnList = Lists.newArrayList();
//        OrderPromotionReqVo reqVo = new OrderPromotionReqVo();
//        List<OrderPromotionReqDetailVo> items = Lists.newArrayList();
//        for(Long productId : vo.getProductIds())
//        {
//            OrderPromotionReqDetailVo rvo = new OrderPromotionReqDetailVo();
//            rvo.setOrderType(OrderTypeEnum.O2O);
//            rvo.setItems();
//
//        }
//        reqVo.setMemberId(Long.valueOf(vo.getMemberId()));
//        List<PromotionBasicInfoVo> items = promotionFeignClient.getPromotion4Order(reqVo);
//        if (items != null && !items.isEmpty()) {
//            items.stream().forEach(item -> {
//                ProductPromotionsInfoResponseVo resp = new ProductPromotionsInfoResponseVo();
//                BeanUtils.copyProperties(item, resp);
//                returnList.add(resp);
//            });
//        }
        return returnList;
    }

}



